import type { renderFunc } from '@lingshu/integration-vue3';
import { Icon } from '@iconify/vue';
import { initMicroAppBus, mainBus, microAppBus } from '@lingshu/communication';
import LsIcon from '@lingshu/icon';
import { initSubVue3, runAppLogic } from '@lingshu/integration-vue3';
import { getCurLanguageType, reloadLatestVersionCache } from '@lingshu/language-lib';
import { useThemeAdapt } from '@lingshu/theme-lib';
import { changeLang as changeBizComponent } from '@minmetals-ui/biz-components';
import ProComponents from '@minmetals-ui/pro-components';
import MiTemplate, { changeLang as changeTemplate } from '@minmetals-ui/template';
import ElementPlusCisdi from 'element-plus-cisdi';
import { createPinia } from 'pinia';
import { createApp, unref } from 'vue';
import Empty from '@/components/empty/index.vue';
import { changeElementPlusLang } from '@/locales/ElementPlusCisdi';
import i18n, { changeLang as changeAppLang } from '@/locales/index';

import App from './App.vue';
import { proxyLanguageRequest } from './locales/TransformRequest';
import router from './router';
import { waringTip } from './utils/WaringTips';
// 条件导入内容
import '@unocss/reset/tailwind-compat.css';
import '__CONDITIONAL_IMPORT__';
import 'virtual:uno.css';
import './styles/index.scss';
import '@minmetals-ui/biz-components/dist/index.css';
import '@minmetals-ui/pro-components/dist/index.css';
import '@minmetals-ui/template/dist/index.css';
import './global.scss';
import '@lingshu/icon/dist/index.css';
import '@lingshu/theme-lib/theme-chalk';
import '@/icons/iconfont/iconfont.css';
import '@/icons/iconfont/iconfont.js';
import '@/styles/common.scss';

const render: renderFunc = async (props) => {
  await runAppLogic({
    // 独立运行时的逻辑，加载语言包版本缓存
    onRunAlone: async () => {
      await Promise.allSettled([
        reloadLatestVersionCache(proxyLanguageRequest).catch(waringTip),
      ]);
    },
    // 在主应用中运行时才会执行的逻辑
    onRunInMain: async () => {
    },
    // 不论是否独立运行，都会在后面执行的逻辑，导入unocss样式
    onRun: async () => {
    },
  });

  if (props?.mainBus) {
    initMicroAppBus(props.mainBus);
  }
  useThemeAdapt({ eventBus: props?.mainBus ? unref(microAppBus) : mainBus });
  const app = createApp(App);

  const languageType = getCurLanguageType();
  // 执行各模块语言包加载逻辑
  await Promise.all([
    changeAppLang({ lang: languageType }),
    changeElementPlusLang({ lang: languageType }),
    changeBizComponent({ lang: languageType, proxyLanguageRequest }),
    changeTemplate({ lang: languageType, proxyLanguageRequest }),
  ]);

  app.use(createPinia());
  app.use(router);
  app.use(ElementPlusCisdi);
  app.use(i18n);
  app.use(MiTemplate);
  app.use(ProComponents);

  app.component('Icon', Icon);
  app.component('hy-empty', Empty);
  app.use(LsIcon);
  app.mount('#app');
};
initSubVue3(render, router);
